var remote_url = "http://127.0.0.1";
$(function(){
	$("input[type=number]").on("focus",function(e){
		if(this.value==0){
			if($(this).attr("readOnly")!="readonly")
				this.value = "";
		}
	}).on("blur",function(e){
		if(this.value==""){
			this.value = 0;
		}
	})
})
function substractText(text){
	text = text.replace(/&nbsp;/g," ");
	while(text.indexOf("<br />")!=-1){
		text = text.replace("<br />","");
	}
	while(text.indexOf("<span")!=-1){
		var beginIndex = text.indexOf("<span");
		var text1 = "";
		if(beginIndex>0){
			text1 = text.substring(0,beginIndex);
			text = text.substring(beginIndex);
			// if(text1.indexOf("/>")==-1&&text1.indexOf("<font")==-1&&text1.indexOf("<i")==-1){
			// 	text1 = '';
			// }
		}
		var endIndex = text.indexOf(">");
		text = text1 + text.substring(endIndex+1);
	}
	while(text.indexOf("</span>")!=-1){
		text = text.replace("</span>","");
	}
	while(text.indexOf("<font")!=-1){
		var beginIndex = text.indexOf("<font");
		var text1 = "";
		if(beginIndex>0){
			text1 = text.substring(0,beginIndex);
			text = text.substring(beginIndex);
		}
		var endIndex = text.indexOf(">");
		text = text1 + text.substring(endIndex+1);
	}
	while(text.indexOf("</font>")!=-1){
		text = text.replace("</font>","");
	}
	while(text.indexOf("<i>")!=-1){
		text = text.replace("<i>","");
	}
	while(text.indexOf("</i>")!=-1){
		text = text.replace("</i>","");
	}
	return text;
}
function genIdWithName(){
	let id = "";
	$.ajax({
		url:"help/genIdWithName",
		type:'get',
		dataType:'html',
		async:false,
		success:function(ret){
			id = ret;
		}
		
	})
	return id;
	
}
function refreshConsole(){
	top.$(".layadmin-tabsbody-item iframe:eq(0)")[0].contentWindow.taskCalendar();
}

function setAutocomplete(url,autocomplete,id,template_val,template_txt,func){
	var elem = typeof(id)=="object" ? id :$('#'+id); 
	
	autocomplete.render({
         	elem: elem,
            url: url,
            statusCode: 0,
            response: {code: 'code', data: 'data'},
            char_limit:0,
         	template_val: template_val,
         	template_txt: template_txt,
         	onselect: function (resp) {
         		if(func){
         			if(typeof(func)=="string"){
         				window[func](resp,elem);
         			}else{
         				func(resp);
         			}
         		}
         		
         	}
    })
}
function genCode(){
	let id = "";
	$.ajax({
		url:"help/genCode",
		type:'get',
		dataType:'html',
		async:false,
		success:function(ret){
			id = ret;
		}
		
	})
	return id;
	
}
function getEntityInfo(id,url){
	var info = {name:""};
	$.ajax({
		url:url,
		type:'POST',
		dataType:'json',
		data:{id: id},
		async:false,
		success:function(ret){
			info = ret;
		}
	})
	return info;
}
function getCityPickerData(){
	var ChineseDistricts = {};
	$.ajax({
		url:'district/getCityPickerList',
		type:'POST',
		dataType:'json',
		async:false,
		success:function(ret){
			ChineseDistricts = ret;
		}
	})
	return ChineseDistricts;
}
function getDistrictPcc(provinceId,cityId,countyId){
	var a = "";
	$.ajax({
		url:"district/getDistrictPcc",
		type:'POST',
		dataType:'html',
		async:false,
		data:{provinceId:provinceId,cityId:cityId,countyId:countyId},
		success:function(ret){
			
			a = ret;
		}
	})
	return a;
}
function formatDate(date,pattern){
	var p = "";
	if(typeof(pattern)=="undefined"){
		p = "YYYY-MM-DD";
	}else{
		p = pattern;
	}
	var res = "";
	if(date){
		res = dayjs(date).format(p);
	}
	return res;
}
function select(url , ele,form,textKey,valueKey,value,placeholder,attrs){
	
	this.attrs = attrs;
	var that = this;
	if(typeof(placeholder)=="undefined"){
		placeholder = "--请选择--";
	}
	if(typeof(attrs)=="undefined"){
		attrs = {};
	}
	var data = [];
	$.ajax({
		url:url,
		type:'POST',
		dataType:'json',
		async: false,
		success:function(ret){
			var option = "";
			let se = $('select[name='+ele+']');
			if(se.children("option").length>0){
				se.children("option:gt(0)").remove();
			}else{
				se.empty();
				if(placeholder){
					option = $("<option value=''>"+placeholder+"</option>");
					option.appendTo(se);
				}
			}
			var keys = Object.keys(attrs);
			for(var i=0;i<keys.length;i++){
				se.attr(keys[i],attrs[keys[i]]);
			}
			if(ret.data){
				data = ret.data;
			}else{
				data = ret;
			}
			
			
			for(var i=0;i<data.length;i++){
				option = $("<option></option>");
				
				option.html(data[i][textKey]).val(data[i][valueKey]);
				if(data[i][valueKey]==value){
				     option.attr("selected",true)
				}
				option.appendTo(se);
				
			}
			if(form){
				form.render();
			}
			if(attrs['callback']){
				setTimeout(function(){
					attrs['callback']();
				},100)	
			}	
		}
	})
	return data;
}

//多选
function xmselect(url , ele,conf){
	var xs;
	if(typeof(conf)=='undefined'){
		conf={key:"id",text:"name"}
	}
	$.ajax({
		url:url,
		type:'POST',
		dataType:'json',
		async:false,
		success:function(ret){
			var data = ret.data;
			var values = [];
			
			for(var i=0;i<data.length;i++){
				values[i] = {name:data[i][conf.text],value:data[i][conf.key]}
			}
			xs = xmSelect.render({
			    el: '#'+ele, 
			    data: values
			})
				
		}
	})
	return xs;
}
//多选
function xmselect_dic(code , ele){
	var xs;
	$.ajax({
		url:'dict/getDictsByParentCode?v='+new Date().getTime(),
		type:'get',
		dataType:'json',
		data:{code:code},
		async:false,
		success:function(ret){
			var data = ret.data;
			var values = [];
			
			for(var i=0;i<data.length;i++){
				values[i] = {name:data[i].name,value:data[i].code}
			}
			xs = xmSelect.render({
				el: '#'+ele, 
				data: values
			})
			
		}
	})
	return xs;
}
function arrSelect(arr , ele,form,value,placeholder){
	if(typeof(placeholder)=="undefined"){
		placeholder = "--请选择--";
	}
	let se = $('select[name='+ele+']').html("");
	
	var option = $("<option value=''>"+placeholder+"</option>");
	option.appendTo(se);
	for(var i=0;i<arr.length;i++){
		var keys = Object.keys(arr[i]);
		option = $("<option></option>");
		option.html(arr[i][keys[0]]).val(keys[0]);
		if(keys[0]==value){
			option.attr("selected",true)
		}
		option.appendTo(se);
				
	}
	if(form){
		form.render();
	}
}
function createSelect(code,ename,form,value,placeholder){
	if(typeof(placeholder)=="undefined"){
		placeholder = "--请选择--";
	}
	$.ajax({
		url:'dict/getDictsByParentCode',
		type:'GET',
		async:false,
		dataType:'json',
		data:{code:code},
		success:function(ret){
			let se = $('select[name='+ename+']');
			var data = ret.data;
			var option = $("<option value=''>"+placeholder+"</option>");
			option.appendTo(se);
			for(var i=0;i<data.length;i++){
				option = $("<option></option>");
				option.html(data[i].name).val(data[i].code);
				if(value==data[i].code){
					option.attr("selected",true);
				}
				option.appendTo(se);
				
			}
			if(form){
				form.render();
			}
		}
	})
}
function createSelectHtml(url,value,placeholder){
	if(typeof(placeholder)=="undefined"){
		placeholder = "--请选择--";
	}
	var selectElement = "";
	$.ajax({
		url:url,
		type:'get',
		async:false,
		dataType:'json',
		success:function(ret){
			let se = $('<select></select>');
			var data = ret.data;
			var option = $("<option value=''>"+placeholder+"</option>");
			option.appendTo(se);
			for(var i=0;i<data.length;i++){
				option = $("<option></option>");
				option.html(data[i].name).val(data[i].code);
				if(value==data[i].code){
					option.attr("selected",true);
				}
				option.appendTo(se);
				
			}
			selectElement = se;
		}
	})
	return selectElement[0].outerHTML
}
function createRadioGroup(code,ename,id,form,value){
	var div = $("#"+id);
	$.ajax({
		url:'dict/getDictsByParentCode',
		type:'GET',
		dataType:'json',
		data:{code: code},
		success:function(ret){
			var data = ret.data;
			for(var i=0;i<data.length;i++){
				var radio = $('<input type="radio" name="'+ename+'" value="'+data[i].code+'" title="'+data[i].name+'">');
				if(typeof(value)!='undefined'){
					if(value==data[i].code){
						radio.attr("checked","");
					}
				}
				radio.appendTo(div);
				
			}
			form.render();
		}
	})
}
function getDictByCode(parentCode,code){
	var dic = {};
	$.ajax({
		url:'dict/getDictByCode?v='+new Date().getTime(),
		type:'POST',
		dataType:'json',
		data:{parentCode: parentCode,code:code},
		async:false,
		success:function(ret){
			dic = ret;
		}
	})
	return dic;
}
function getDictValue(code,key){
	var dict = getDictByCode(code,key);
	if(dict.name==null){
		  return "";
	}else{
		  return dict.name;
	}
}
function getUrlParam(k) {
    var regExp = new RegExp('([?]|&)' + k + '=([^&]*)(&|$)');
    var result = window.location.href.match(regExp);
    if (result) {
        return decodeURIComponent(result[2]);
    } else {
        return null;
    }
}
function clickLayTableRow(table,form,filter,obj){
	var data = table.cache[filter];
    var rowIndex = obj.tr.data("index");
    let targetElem = $(event.target);
    if(targetElem.is(".layui-icon-ok")||targetElem.is("layui-anim-scaleSpring")){
        let checkState = data[rowIndex][table.config.checkName];
        if(typeof(checkState)=="undefined"||!checkState){
        	obj.tr.addClass("layui-table-click").removeClass('layui-table-hover');
        }else{
        	obj.tr.removeClass("layui-table-click");
        }
        return false;
    }else{
        obj.tr.closest("tbody").find(".layui-table-click").removeClass("layui-table-click").removeClass('layui-table-hover');;
        obj.tr.addClass("layui-table-click");
        var c = obj.tr.find("input[name=layTableCheckbox],:radio[lay-type=layTableRadio]");
        var oldc = obj.tr.closest("table").find(":input[name=layTableCheckbox]:checked,:radio[lay-type=layTableRadio]:checked").prop("checked",false);
        oldc.each(function(i,v){
            var oldcIndex = $(v).closest("tr").data("index");
            if(typeof(oldcIndex)!=="undefined"){
            	try{
            		data[oldcIndex][table.config.checkName] = false;
            	}catch(e){
            	
            	}
            }
            	
        })
        c.prop("checked",true);
        try{
        	data[obj.tr.data("index")][table.config.checkName] = true;
        }catch(e){
        	
        }	
        
        form.render();
     }
}

function enableRowClick(table,form,filter,id,fn){
	var tb = $('div[lay-id='+filter+']');
	tb.find('tr[data-index] td:not(:has(:input[name=layTableCheckbox]),[data-field=0]),tr[data-index] td:not(:has(:radio[lay-type=layTableRadio]),[data-field=0])').click(function(e){
		var tr = $(e.target).closest("tr");
		selectRow(table,form,filter,id,tr,fn);
	})   
}
function selectRow(table,form,filter,id,tr,fn){
	var data = table.cache[id];
	var tb = $('div[lay-id='+filter+']');
	var index = tr.data("index");
	var c = tr.find("input[name=layTableCheckbox],:radio[lay-type=layTableRadio]");
	var oldc = tb.find("input[name=layTableCheckbox]:checked,:radio[lay-type=layTableRadio]:checked").prop("checked",false);
	oldc.each(function(i,v){
		var oldcIndex = $(v).closest("tr").data("index");
		if(typeof(oldcIndex)!=="undefined")
			data[oldcIndex][table.config.checkName] = false;
	})
	c.prop("checked",true);
	var tableBox = tr.closest('.layui-table-box');
	tableBox.find(".layui-table-click").removeClass("layui-table-click");
	tableBox.find(".layui-table-hover").addClass("layui-table-click");
	tb.find('tr[data-index='+tr.data("index")+'] .layui-form-checkbox,tr[data-index='+tr.data("index")+'] .layui-form-radio').each(function(i,v){
		$(v.parentNode).find(":input[type=checkbox],:radio").prop("checked",true)
		$(v).addClass("layui-form-checked");
	})
	if(data[index]){
		data[index][table.config.checkName] = true;
		form.render("checkbox");
		form.render("radio");
		if(typeof(fn)!="undefined"){
			window[fn]();
		}
	}
	
	
}
function selectRow2(table,form,filter,id,tr,fn){
	var data = table.cache[id];
	var tb = $('div[lay-id='+filter+']');
	var index = tr.data("index");
	var c = tr.find("input[name=layTableCheckbox]");
	c.prop("checked",true);
	var tableBox = tr.closest('.layui-table-box');
	tb.find('tr[data-index='+tr.data("index")+'] .layui-form-checkbox').each(function(i,v){
		$(v.parentNode).find(":input[type=checkbox]").prop("checked",true)
		$(v).addClass("layui-form-checked");
		$(v).closest("tr").addClass("layui-table-click");
	})
	form.render("checkbox");
	data[index][table.config.checkName] = true;
	if(typeof(fn)!="undefined"){
		window[fn]();
	}
}
//设置指定行为选中状态
function selectedRows(checkData,table,form,filter,id,params){
	 setTimeout(function(){
		 var idName = "id";
		 if(typeof(params)!=="undefined"){
			 idName = params.idName;
		 }
		 if(typeof(checkData)=="string"){
			 var jobj = {};
			 jobj[idName] = checkData
			 checkData = [jobj]	
		 }
		 for(var i=0;i<checkData.length;i++){
			 var text = checkData[i][idName];
			  var divs = $('td[data-field='+idName+']:contains('+text+')');
			  if(divs.length>0){
				  var div = divs.filter(function(d){
					  return this.innerText == text;
				  })
				  var tr = div.closest("tr");
				  var checkBox = tr.find("input[name=layTableCheckbox]");
				  selectRow2(table,form,filter,id,tr);
			  }
		 }
	  },100);
}
//只能输入整数
function onlyDigit(e){  
    var charCode = e.charCode ? e.charCode : e.keyCode;  
    if(charCode<48 || charCode >57){  
        return false;  
    }else{  
        return true;      
    }  
} 
//输入时限制只能输入数字（含小数）
function onlyNumber(){
	return (/[\d.]/.test(String.fromCharCode(event.keyCode)));
}

function isNumber(num)
{
	
     var re = /^[\d.]+$/;      
     if (!re.test(num))
    {
        return false;
     }
     return true;
}

function accMul(arg1,arg2){  
	var m=0,s1=arg1.toString(),
	s2=arg2.toString();  
	try{
	m+=s1.split(".")[1].length}catch(e){}  
	try{
	m+=s2.split(".")[1].length}catch(e){}  
	return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
}
function accDiv(arg1, arg2) {
    var r1 = arg1.toString(), r2 = arg2.toString(), m, resultVal, d = arguments[2];
    m = (r2.split(".")[1] ? r2.split(".")[1].length : 0) - (r1.split(".")[1] ? r1.split(".")[1].length : 0);
    resultVal = Number(r1.replace(".", "")) / Number(r2.replace(".", "")) * Math.pow(10, m);
    return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)));
}

function accAdd(arg1,arg2){ 
	var r1,r2,m;  
	try{
	r1=arg1.toString().split(".")[1].length
	}catch(e){
	r1=0}  try{
	r2=arg2.toString().split(".")[1].length}catch(e){r2=0}  m=Math.pow(10,Math.max(r1,r2))  
	return (arg1*m+arg2*m)/m
}
function accSub(arg1, arg2) {
    return accAdd(arg1, -Number(arg2), arguments[2]);
}
function format45(val,v2) {
	
    if (isNaN(val) || val == undefined || val == null) 
    {
    	return null; 
    }
    return Math.round(val * v2) / v2;
}
function getCurrentTime(pattern){
	if(typeof(pattern)=="undefined"){
		pattern = "yyyy-MM-dd";
	}
	var ret = "";
	$.ajax({
		url: 'help/getCurrentTime',
		async:false,
		type:'GET',
		dataType:'html',
		data:{pattern:pattern},
		success:function(v){
			ret = v;
		}
	})
	return ret;
}
function getSigleValueFromServer(data,url){
	var v = 0;
	$.ajax({
		  url: url,
		  type:'POST',
		  dataType:'JSON',
		  data:data,
		  async:false,
		  success:function(ret){
			  v = ret;
		  }
	  })
	  return v;
}
function getUserById(id){
	var ret = "";
	$.ajax({
		url: 'user/getById',
		async:false,
		data:{id:id},
		type:'POST',
		dataType:'json',
		success:function(v){
			ret = v;
		}
	})
	if(!ret){
		ret = "";
	}
	return ret;
}
function getOrgById(id){
	var ret = "";
	$.ajax({
		url: 'org/getById',
		async:false,
		data:{id:id},
		type:'POST',
		dataType:'json',
		success:function(v){
			ret = v;
		}
	})
	if(!ret){
		ret = "";
	}
	return ret;
}
function getOrgByCode(code){
	var ret = "";
	$.ajax({
		url: 'org/getByCode',
		async:false,
		data:{code:code},
		type:'POST',
		dataType:'json',
		success:function(v){
			ret = v;
		}
	})
	if(!ret){
		ret = "";
	}
	return ret;
}

function isMobileno(value) {  
    var myreg=/^[1][3,4,5,6,7,8,9][0-9]{9}$/;  
    if (!myreg.test(value)) {  
        return false;  
    } else {  
        return true;  
    }  
}
function uuid() {
	function S4() {
		return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
	}
	//return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
	return (S4() + S4()  + S4() + S4() + S4() + S4() + S4() + S4());
}
var Snowflake = (function() {
    function Snowflake(_workerId, _dataCenterId, _sequence) {
        this.twepoch = 1288834974657n;
        //this.twepoch = 0n;
        this.workerIdBits = 5n;
        this.dataCenterIdBits = 5n;
        this.maxWrokerId = -1n ^ (-1n << this.workerIdBits); // 值为：31
        this.maxDataCenterId = -1n ^ (-1n << this.dataCenterIdBits); // 值为：31
        this.sequenceBits = 12n;
        this.workerIdShift = this.sequenceBits; // 值为：12
        this.dataCenterIdShift = this.sequenceBits + this.workerIdBits; // 值为：17
        this.timestampLeftShift = this.sequenceBits + this.workerIdBits + this.dataCenterIdBits; // 值为：22
        this.sequenceMask = -1n ^ (-1n << this.sequenceBits); // 值为：4095
        this.lastTimestamp = -1n;
        //设置默认值,从环境变量取
        this.workerId = 1n;
        this.dataCenterId = 1n;
        this.sequence = 0n;
        if (this.workerId > this.maxWrokerId || this.workerId < 0) {
            throw new Error('_workerId must max than 0 and small than maxWrokerId-[' + this.maxWrokerId + ']');
        }
        if (this.dataCenterId > this.maxDataCenterId || this.dataCenterId < 0) {
            throw new Error('_dataCenterId must max than 0 and small than maxDataCenterId-[' + this.maxDataCenterId + ']');
        }

        this.workerId = BigInt(_workerId);
        this.dataCenterId = BigInt(_dataCenterId);
        this.sequence = BigInt(_sequence);
    }
    Snowflake.prototype.tilNextMillis = function(lastTimestamp) {
        var timestamp = this.timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = this.timeGen();
        }
        return BigInt(timestamp);
    };
    Snowflake.prototype.timeGen = function() {
        return BigInt(Date.now());
    };
    Snowflake.prototype.nextId = function() {
        var timestamp = this.timeGen();
        if (timestamp < this.lastTimestamp) {
            throw new Error('Clock moved backwards. Refusing to generate id for ' +
                (this.lastTimestamp - timestamp));
        }
        if (this.lastTimestamp === timestamp) {
            this.sequence = (this.sequence + 1n) & this.sequenceMask;
            if (this.sequence === 0n) {
                timestamp = this.tilNextMillis(this.lastTimestamp);
            }
        } else {
            this.sequence = 0n;
        }
        this.lastTimestamp = timestamp;
        return ((timestamp - this.twepoch) << this.timestampLeftShift) |
            (this.dataCenterId << this.dataCenterIdShift) |
            (this.workerId << this.workerIdShift) |
            this.sequence;
    };
    return Snowflake;
}());
function snowId(){
	var tempSnowflake = new Snowflake(1n, 1n, 0n);
	var tempId = tempSnowflake.nextId();
	return tempId;
}

function addEditTableRow(ts,fn){
	var table = $(ts.elem);
	var tbody = table.find("tbody");
	var tr = $("<tr>").prependTo(tbody);
	tr.attr("editing",true).attr("id",uuid());
	tr.on("click",function(ev){
		$("tr.layui-table-click").removeClass("layui-table-click");
		$(this).addClass("layui-table-click");
		tbody.find("div[name=layui-select-flag]>div.layui-form-checkbox").removeClass("layui-form-checked")
		$(this).find("div[name=layui-select-flag]>div.layui-form-checkbox").addClass("layui-form-checked")
	})
	for(setting of ts.cols){
		var td = $("<td style='padding-left:3px'>").attr("field-name",setting.name);
		td.appendTo(tr);
		var tdwidth = td.width()-2;
		
		switch(setting.type){
		case "hidden":
			td.attr("value","").hide();
			break;
		case "checkbox":
			var div = $('<div name="layui-select-flag" class="layui-table-cell laytable-cell-checkbox">');
			var checkbox = $('<input type="checkbox" lay-skin="primary" name="layui-select-flag">');
			checkbox.appendTo(div);
			td.append(div);
			var div2 = $('<div class="layui-unselect layui-form-checkbox" lay-skin="primary">'); 
			var i = $("<i>").addClass("layui-icon layui-icon-ok").appendTo(div2);
			div.append(div2);
			break;
		case "textarea":
			var textarea = $("<textarea style='border-color: #e6e6e6;width:"+tdwidth+"px!important; height:38px;display:block'>");
			textarea.appendTo(td);
			break;
		case "input":
		case "number":
			var input = $("<input style='"+setting.type+"' style='border-color: #e6e6e6;display:block' class='layui-input'>").width(tdwidth-2).height(td.height());
			input.appendTo(td);
			break;
		case "select":
			if(setting.dic){
				var se = $(setting.selection).appendTo(td);
				se.addClass("okselect").show();
			}
			break;
		case "date":
			input = $('<input style="width:'+tdwidth+'px!important;margin:0 auto" class="layui-input">').appendTo(td);
			layui.use("laydate",function(){
				var laydate = layui.laydate;
				laydate.render({
					elem: input[0]
				});
			})
			break;
		case "popwin":
			let tempSetting = setting;
			var url = tempSetting.url;
			var input = $('<input style="width:'+tdwidth+'px!important;margin:0 auto" class="layui-input">');
			input.appendTo(td);
			input.on("click",function(e){
				$(":input[currentElement]").removeAttr("currentElement");
				$(this).attr("currentElement",true);
				top.layer.open({
		            type: 2,
		            title:'选择',
		            area:['1200px',(top.height-50)+'px'],
		            content:  tempSetting.url,
		            btn:['关闭']
		        });
			})
			break;
		case "popwinok":
			var url = setting.url;
			var input = $('<input style="width:'+tdwidth+'px!important;margin:0 auto" class="layui-input">');
			input.appendTo(td);
			input.on("click",function(e){
				$(":input[currentElement]").removeAttr("currentElement");
				$(this).attr("currentElement",true);
				top.layer.open({
		            type: 2,
		            title:'选择部门',
		            area:['1200px',(top.height-50)+'px'],
		            content:  url,
		            btn:['确定','关闭'],
		            yes:function(index,layero){
		            	var iframeWin = top[layero.find('iframe')[0]['name']];
		            	var nodes = iframeWin.treeObj.getSelectedNodes();
		            	if(nodes.length==1){
		            		var obj = $(e.target);
		            		e.target.value = nodes[0].name;
		            		obj.data('value', nodes[0].id);
		            		obj.closest("td").data("value",nodes[0].id);
		            	}
		            	top.layer.close(index)
		                return false
		            }
		        });
			})
			break;
		}
	}
	if(fn){
		fn(tr);
	}
	return tr;
}
function createEditTable(ts){
	var table = $(ts.elem);
	var thead = $("<thead>").appendTo(table);
	var headtr = $("<tr>").appendTo(thead);
	table.closest("div.layui-form").height(ts.height);
	for(setting of ts.cols){
		var th = $("<th>").appendTo(headtr).attr("field-name",setting.name);
		if(setting.type==="checkbox"){
			th.width(30)
			th.html("").attr("name","allcheck")
			var div = $('<div class="layui-table-cell laytable-cell-checkbox">');
			var checkbox = $('<input type="checkbox" lay-skin="primary">').appendTo(div);
			table.find("th[name=allcheck]").append(div);
		}else if(setting.type=="numbers"){
			th.width(30)
			th.html("").attr("name","numbers")
		}else if(setting.title){
			if(setting.type=="hidden"){
				th.hide();
			}else{
				th.html(setting.title).width(setting.width);
			}
			if(typeof(setting.dic)!="undefined"){
				var se = createSelectHtml("dict/getDictsByParentCode?code="+setting.dic,"");
				setting.selection = se;
			}
		}
	}
	var tbody = $("<tbody>");
	table.append(tbody);
	reloadEditable(ts);
}
function reloadEditable(ts){
	var data = {limit:ts.limit, page:ts.page};
	if(typeof(ts.data)!="undefined"){
		let keys = Object.keys(ts.data);
		for(key of keys){
			data[key] = ts.data[key];
		}
	}
	$.ajax({
		url:ts.url,
		type:'post',
		dataType:'json',
		data: data,
		success:function(res){
			layui.use("laypage",function(){
				layui.laypage.render({
					elem:"item-table-page"
					,layout: ['prev', 'count','page', 'next', 'limit', 'skip']
					,count:res.count
					,curr:ts.page
					,jump:function(obj,first){
						if(!first){
							ts.page = obj.curr;
							reloadEditable(ts);
						}
					}
				})
			})
			var datas = res.data;
			var table = $(ts.elem);
			var tbody = table.find("tbody");
			tbody.html("");
			for(var i=0;i<datas.length;i++){
				var data = datas[i];
				var tr = $("<tr>");
				tbody.append(tr);
				tr.on("click",function(ev){
					$("tr.layui-table-click").removeClass("layui-table-click");
					$(this).addClass("layui-table-click");
					tbody.find("div[name=layui-select-flag]>div.layui-form-checkbox").removeClass("layui-form-checked")
					$(this).find("div[name=layui-select-flag]>div.layui-form-checkbox").addClass("layui-form-checked")
				})
				for ( setting of ts.cols ) {
					let td = $("<td style='padding-left:3px'>").appendTo(tr);
					if (setting.type==="checkbox") {
						var checkbox = $("<input type='checkbox' name='layui-select-flag' lay-skin='primary'>");
						var div = $('<div name="layui-select-flag" class="layui-table-cell laytable-cell-checkbox">');
						div.append(checkbox);
						
						td.append(div);
						var div2 = $("<div>").addClass("layui-unselect layui-form-checkbox").attr("lay-skin","primary");
						div.append(div2);
						var icon = $("<i>").addClass("layui-icon layui-icon-ok");
						icon.appendTo(div2);
						td.on("click",function(ev){
							$(this).find("div.layui-form-checkbox").addClass("layui-form-checked");
							ev.stopPropagation();
						})
					}else if(setting.type=="numbers"){
						td.html(i+1);
					}else if(setting.type==="hidden"){
						td.attr("field-name",setting.name).hide();
						td.data("value",data[setting.name]);
						
					}else{
						td.attr("field-name",setting.name);
						let tempSetting = setting;
						
						td.on('click',function(ev){
							let tdobj = $(this);
							if(tdobj.attr("clickEdit")){
								return false;
							}
							if(typeof(ts.editable)=='undefined'||ts.editable){
								clickEditableTd(tdobj,table,tempSetting,ev);
							}
							
						})
						td.data("value",data[setting.name]);
						if(setting.showName){
							td.html(data[setting.showName]);
						}else{
							td.html(data[setting.name]);
						}
						
					}
				}
			}
			if(ts.done){
				ts.done();
			}
		}
	})

}
function clickEditableTd(tdobj,table,tempSetting,ev){
	
	tdobj.parents("tr").click();
	$("body").one("click",function(){
		if(tdobj.attr("clickEdit")){
		    var newvalue = "";
			var oldvalue = tdobj.data("value");
			oldvalue = oldvalue==null?"":oldvalue;
			switch(tempSetting.type){
				case "select":
					var selectedOption = tdobj.find("select option:selected");
					tdobj.html(selectedOption.text());
					newvalue = selectedOption.val();
					tdobj.data("value",newvalue);
					break;
				case "input":
				case "number":
					newvalue = tdobj.find("input").val();
					tdobj.html(newvalue).data("value",newvalue);
					break;
			}
			if(oldvalue!==newvalue&&tempSetting.edit&&typeof(tempSetting.edit)=="function"){
				tempSetting.edit(getEditableRowData(tdobj.parent('tr')));
			}
								
			tdobj.removeAttr("clickEdit");
		}
	})
	/**prevTd开始**/
	var prevTd = table.find("td[clickEdit]");
	if(prevTd[0]!==this&&prevTd.length==1){
		var fieldName = prevTd.attr("field-name");
		var prevSetting = ts.cols.filter(e=>e.name==fieldName)[0];
		var oldvalue = prevTd.data("value");
		oldvalue = oldvalue==null?"":oldvalue;
		var newvalue = "";
		prevTd.removeAttr("clickEdit");
		switch(prevSetting.type){
			case "select":
				var selectedOption = prevTd.find("select option:selected");
				prevTd.html(selectedOption.text());
				newvalue = selectedOption.val();
				prevTd.data("value",newvalue);
				break;
			case "input":
			case "number":
				let txt = prevTd.find("input").val();
				prevTd.html(txt).data("value",txt);
				newvalue = txt;
				break;
			}
			if(oldvalue!==newvalue&&prevSetting.edit&&typeof(prevSetting.edit)=="function"){
				prevSetting.edit();
			}
	}
	/**prevTd结束**/
	switch(tempSetting.type){
		case 'select':
			if(tempSetting.selection){
				tdobj.attr("clickEdit",true);
				var selection = tempSetting.selection;
				if($(this).find("select").length==0){
					this.innerHTML = "";
					var se = $(selection);
					se.val($(this).data("value"));
					se.appendTo(tdobj);
					se.addClass("okselect").show();
				}
			}
			break;
		case 'input' :
		case 'number' :
			if(tdobj.find("input").length==0){
				tdobj.attr("clickEdit",true);
				let text = tdobj.html();
				tdobj.html("");
				let input = $("<input type='"+tempSetting.type+"' style='border-color: #e6e6e6;display:block'>").addClass("layui-input").width(tdobj.width()-2).height(tdobj.height());
				input.appendTo(tdobj);
				input.val(text).select().focus()
			}
			break;
	}
	ev.stopPropagation();
}
//获取一行的数据
function getEditableRowData(tr){
	var data = {trid:tr.attr("id")};
	var tds = tr.find("td[field-name]");
	tds.each(function(j,td){
		var name = $(td).attr("field-name");
		if($(td).data("value")){
			data[name] = $(td).data("value");
		}else{
			var input = $(td).find(":input,select");
			if(input.length==0){
				data[name] = $(td).text();
			}else{
				if(input.data("value")){
					data[name] = input.data("value");
				}else{
					data[name] = input.val();
				}
			}
		}
	})
	return data;
}
//获取选中的行数据
function getEditableSelectedRows(tableId){
	var trs = $("#"+tableId).find("div.layui-form-checked").parents("tr");
	var res = {trs:trs};
	var datas = [];
	trs.each(function(i,v){
		var tr = $(v);
		data = getEditableRowData(tr);
		datas.push(data);
	})
	res.datas = datas;
	return res;
}
//获取正在编辑的行数据
function getEditableEditingRows(tableId){
	var trs = $("#"+tableId+" tr[editing]");
	var res = {trs:trs};
	var datas = [];
	trs.each(function(i,v){
		var data = {};
		var tr = $(v);
		var tds = tr.find("td[field-name]");
		tds.each(function(j,td){
			var name = $(td).attr("field-name");
			if($(td).data("value")){
				data[name] = $(td).data("value");
			}else{
				var input = $(td).find(":input,select");
				if(input.length==0){
					data[name] = $(td).text();
				}else{
					if(input.data("value")){
						data[name] = input.data("value");
					}else{
						data[name] = input.val();
					}
				}
			}
			
		})
		datas.push(data);
	})
	res.datas = datas;
	return res;
}

function getTabWin(id){
	let win = null;
	if(id){
		let obj = top.$("#"+id+" iframe")[0];

		if(obj){
			win = obj.contentWindow;
		}
		
	}else{
		var topul = $(top.document).find("#LAY_app_tabsheader");
		if(topul.length==0){
			return parent;
		}
		let  tagIndex = topul.find("li").index(topul.find(".layui-this"));
		win = $(top.document).find("#LAY_app_body>div").eq(tagIndex).find("iframe")[0].contentWindow;
	}
	
	return win;
}
function getLaybody(tableId){
	return $("div[lay-id="+tableId+"] div.layui-table-body");
}
function updateLayuiCellValue(tableId,id,fieldName,value){
	var tr = $('div[lay-id='+tableId+']').find("td[data-field=id]:contains("+id+")").closest("tr");
    tr.find("td[data-field="+fieldName+"] div").html(value);
}
function updateLayRow(table,tableId,kv,names){
	var checkStatus = table.checkStatus(tableId);
	var laybody = getLaybody(tableId);
	let allRowData = table.cache[tableId];
	let rowData = allRowData.filter(v=>v.id === kv.id)
	let rowIndex = rowData[0]["LAY_TABLE_INDEX"];
	let tr = laybody.find('tr[data-index='+ rowIndex +']');
	let keys = names || Object.keys(kv);
	for(const k of keys){
		let td = tr.children('td[data-field='+k+']');
		td.children(".layui-table-cell").html(kv[k]);
	}
}
function updateLayRowByIndex(table,tableId,rowIndex,kv){
	var laybody = getLaybody(tableId);
	let tr = laybody.find('tr[data-index='+ rowIndex +']');
	let keys = Object.keys(kv);
	for(const k of keys){
		let td = tr.children('td[data-field='+k+']');
		td.children(".layui-table-cell").html(kv[k]);
	}
	
}

function waterMark(markElement) {
	$('#' + markElement.waterMarkId).find('.markElement').remove();
	var settings = {
		waterMarkId:"t1",
		waterMarkContent:"我是水印内容",
		waterMarkX:120,
		waterMarkY:140,
		waterMarkRows:1,
		waterMarkCols:1,
		waterMarkXSpace:0,
		waterMarkYSpace:0,
		waterMarkColor:'blue',
		waterMarkAlpha:0.5,
		waterMarkFontSize:'25px',
		waterMarkFont:'仿宋',
		waterMarkWidth:100,
		waterMarkHeight:100,
		waterMarkAngle:15
	};
	if(arguments.length === 1 && typeof arguments[0] === "object" ) {
		var src = arguments[0]||{};
		for(key in src) {
			if(src[key]&&settings[key] && src[key] === settings[key])
				continue;
			else if(src[key])
				settings[key] = src[key];
		}
	}
	var obj = document.getElementById(settings.waterMarkId);
	var tmpObj = document.createDocumentFragment();
	var pageWidth = obj.offsetWidth; 
	var pageHeight = obj.offsetHeight ;
	if (settings.waterMarkCols == 0 || (parseInt(settings.waterMarkX + settings.waterMarkWidth *settings.waterMarkCols + settings.waterMarkXSpace * (settings.waterMarkCols - 1)) > pageWidth)) {
		settings.waterMarkCols = parseInt((pageWidth-settings.waterMarkX+settings.waterMarkXSpace) / (settings.waterMarkWidth + settings.waterMarkXSpace));
		settings.waterMarkXSpace = parseInt((pageWidth - settings.waterMarkX - settings.waterMarkWidth * settings.waterMarkCols) / (settings.waterMarkCols - 1));
	}
	if (settings.waterMarkRows == 0 || (parseInt(settings.waterMarkY + settings.waterMarkHeight * settings.waterMarkRows + settings.waterMarkYSpace * (settings.waterMarkRows - 1)) > pageHeight)) {
		settings.waterMarkRows = parseInt((settings.waterMarkYSpace + pageHeight - settings.waterMarkY) / (settings.waterMarkHeight + settings.waterMarkYSpace));
		settings.waterMarkYSpace = parseInt(((pageHeight - settings.waterMarkY) - settings.waterMarkHeight * settings.waterMarkRows) / (settings.waterMarkRows - 1));
	}
	var x;
	var y;
	settings.waterMarkRows = settings.waterMarkRows == 0 ? 6 : settings.waterMarkRows; 
	for (var i = 0; i < settings.waterMarkRows; i++) {
		y = settings.waterMarkY + (settings.waterMarkYSpace + settings.waterMarkHeight) * i;
		y = isNaN(y) ? 40 : y;
		for (var j = 0; j < settings.waterMarkCols; j++) {
			x = settings.waterMarkX + (settings.waterMarkWidth + settings.waterMarkXSpace) * j;
			var markElement = document.createElement('div');
			markElement.style.border = "1px solid blue";
			markElement.id = 'markElement' + i + j;
			markElement.appendChild(document.createTextNode(settings.waterMarkContent));
			//设置水印div倾斜显示
			markElement.style.webkitTransform = "rotate(-" + settings.waterMarkAngle + "deg)";
			markElement.style.MozTransform = "rotate(-" + settings.waterMarkAngle + "deg)";
			markElement.style.msTransform = "rotate(-" + settings.waterMarkAngle + "deg)";
			markElement.style.OTransform = "rotate(-" + settings.waterMarkAngle + "deg)";
			markElement.style.transform = "rotate(-" + settings.waterMarkAngle + "deg)";
			markElement.style.visibility = "";
			markElement.style.position = "absolute";
			markElement.style.left = x + 'px';
			markElement.style.top = y + 'px';
			markElement.style.overflow = "hidden";
			markElement.style.zIndex = "10";
			markElement.style.padding = "5px";
			markElement.style.opacity = settings.waterMarkAlpha;
			markElement.style.fontSize = settings.waterMarkFontSize;
			markElement.style.fontFamily = settings.waterMarkFont;
			markElement.style.color = settings.waterMarkColor;
			markElement.style.textAlign = "center";
			//markElement.style.width = settings.waterMarkWidth + 'px';
			//markElement.style.height = settings.waterMarkHeight + 'px';
			markElement.style.display = "block";
			markElement.style.filter = "alpha(opacity="+ settings.waterMarkAlpha*100 +")";
			markElement.setAttribute("class","markElement");
			tmpObj.appendChild(markElement);
		};
	};
	obj.appendChild(tmpObj);
}